from flask import Flask, render_template, request,session, redirect
import os,redis, copy,json
import os,redis, copy,json
from flask_cors import *
import lei,operation,polygon
import uuid,random
from flask_uploads import configure_uploads,UploadSet

app = Flask(__name__)
CORS(app, resources=r'/*')

app.config['SECRET_KEY'] = 'abc'

r = redis.StrictRedis(host='localhost', port=6379, db=0)


#配置上传文件存放路径
base=os.path.dirname(os.path.abspath(__file__))
base = os.path.join(base,'static')
app.config['UPLOADS_DEFAULT_DEST']=base
photo=UploadSet()
configure_uploads(app,photo)


# app.config['SESSION_TYPE'] = 'redis'   #session存储格式为redis
# app.config['SESSION_REDIS'] = Redis(    #redis的服务器参数
#     host='127.0.0.1',     #服务器地址
#     port=6379)                           #服务器端口
# app.config['DEBUG']=True
# app.config['SESSION_PERMANENT'] = False  #sessons是否长期有效，false，则关闭浏览器，session失效
# app.config['PERMANENT_SESSION_LIFETIME'] = 3600   #session长期有效，则设定session生命周期，整数秒，默认大概不到3小时。
# Session(app)


#路由
@app.route("/")
def hello():

    return "Hello world!"

@app.route("/main",methods=("POST","GET"))
def index():

    return render_template("index.html")


@app.route("/imgRestore",methods=("POST","GET"))
def img():

    if request.method == "POST":
        file = request.files['file']
        suffix = file.filename.split(".")[1]#获取后缀名
        name= str(uuid.uuid1())
        filename = name+'.'+suffix
        photo.save(request.files['file'], 'img',filename)#保存图片
        r.set('imgName',filename)
    return 'hahah'

@app.route("/points_redis",methods=("POST","GET"))
@cross_origin()
def points_redis():

    points = request.json
    print(polygon.multi_area(points))
    print(points)
    a = polygon.array2d(points)

    #退线操作。
    retreat = int(r.get('retreat'))
    arr = operation.retreat(a, {'dis_w':retreat, 'dis_e':retreat, 'dis_n':retreat, "dis_s":retreat})
    r.set("a", str(arr))

    temparr = copy.deepcopy(arr)
    r.set("temparr",str(temparr))
    #b = lei.builds(temparr)

    if request.method == "POST":
        args = request.json
    print("准备运行算法")
    rate = float(r.get('rate').decode('utf8'))
    density = float(r.get('density').decode('utf8'))
    type = eval(r.get('type').decode('utf8'))
    ll = lei.showbuildings(rate,density,arr,type)
    print("运算完成")
    # for i in range(10):#生成dict
    #     #由于装载dict在前后端产生了诸多问题，所以改用list[list]
    #
    #     plan=[]
    #     plan.append(i)                               #plan[0] = pid
    #     plan.append(50000+random.randint(4000,20000))  #plan[1] = money
    #     p = random.uniform(2, 3.5)
    #     plan.append(round(p,1))                     #plan[2] = sun
    #     q = random.uniform(0.28,0.32)
    #     plan.append(round(q,2))                    #plan[3] = density
    #     plan.append(b)                            #plan[4] = builds数组
    #     ll.append(plan)
    # print(ll)

    r.set('all',str(ll))
    return '我giao'

@app.route("/getImg")
def getImg():
    # img = open("/static/files/img1/pic.png", 'rb')  # 读取图片文件
    # data = base64.b64encode(img.read()).decode()  # 进行base64编码
    # html = '''<img src="data:image/png;base64,{}" style="position: absolute;z-index: 1;left:0;top:0;background: #e3fefd;cursor:crosshair;width:1000px;height:1000px;border:2px solid black;"/>'''  # html代码
    # htmlstr = html.format(data)  # 添加数据
    # print("到这没问题，取完img文件")
    # return htmlstr
    imgName = r.get("imgName")

    return imgName

@app.route("/test")
def test():
    d = {"dis_n":6,"dis_s":6,"dis_e":6,"dis_w":6}
    l= operation.sort_by_value(d)
    print(l[0])
    print(d.get(l[3]))
    return render_template("Submit.html")

@app.route('/temp',methods=("GET","POST"))
def temp():
    print("HELLO:", end=" ")
    pid = 0
    imgName = r.get("imgName")
    if request.args.get("pid"):
        pid = request.args.get("pid")
    ll = r.get('all')
    plans = eval(ll.decode('utf8'))

    for plan in plans:
        if int(plan[0])==int(pid):
            builds = plan[4]
            print('我可以确信我更新了builds的内容')
    #List内有多个dict，dict：{ id:? , density:? ,money:? , sun:? , builds:? }
    arr = r.get("a").decode('utf-8')
    temparr = r.get("temparr").decode('utf-8')
    data = {
        'pid':pid,
        'arr':arr,
        'temparr':temparr,
        'plans':plans,
        'builds':builds,
        'imgName':imgName.decode('utf-8'),
    }

    print(builds)
    return render_template('temp.html', data=data)


@app.route("/vue_test")
def v():
    return render_template("vue_test.html")
@app.route("/axios")
def a():
    return '我有很多小王八'


@app.route("/submit")
def submit():
    return render_template("Submit.html")

@app.route("/search",methods=("POST","GET"))
def search():
    # form = request.form
    # args = form.get("choose")
#   arr = paibu(args) #将dict中的数据 根据用户选择的排序指标进行排序


    args = request.json  # 获取到用户想要根据什么存储
    # XX(args)   根据这个条件对各个数据集进行排序
    print(args)



    plans = r.get("all").decode('utf8')
    pp=eval(plans)
    print(pp)
    pps = sorted(pp, key=lambda x:x[args])
    print(pps)
    data = {
        'plans': pps,
    }
    t = json.dumps(data)
    return t

@app.route("/select",methods=("POST","GET"))
def shapeSelect():
    user = session.get('user')
    if not user:
        return redirect('/login')

    form = request.form
    print(form)
    condi = operation.Condi(form)

    r.set('rate', form.get('rate'));
    r.set('density', form.get('density'))
    r.set('retreat', form.get('retreat'))

    data=[]
    data0 = {
        'src':"/static/img/GaoCeng01.png",
        'id':1,
        'square':411,
        'price':30500
    }
    data.append(data0)
    data1 = {
        'src':"/static/img/GaoCeng02.png",
        'id':2,
        'square':411,
        'price':30100
    }
    data.append(data1)
    data2 = {
        'src':"/static/img/GaoCeng03.png",
        'id':3,
        'square':442,
        'price':27030
    }
    data.append(data2)
    data3 = {
        'src':"/static/img/GaoCeng04.png",
        'id':4,
        'square':442,
        'price':20304
    }
    data.append(data3)
    data4 = {
        'src':"/static/img/paiwu01.png",
        'id':1,
        'square':260,
        'price':40030
    }
    data.append(data4)
    data5 = {
        'src': "/static/img/paiwu02.png",
        'id': 2,
        'square': 260,
        'price': 40800
    }
    data.append(data5)
    data6 = {
        'src': "/static/img/YangFang01.png",
        'id': 1,
        'square': 190,
        'price': 20030
    }
    data.append(data6)
    data7 = {
        'src': "/static/img/YangFang02.png",
        'id': 2,
        'square': 190,
        'price': 20200
    }
    data.append(data7)
    return render_template("select.html",data=data)

@app.route('/typeReturn',methods=("GET","POST"))
def typeReturn():
    selectArray = request.get_data()
    json_re = json.loads(selectArray)
    orderlist=[0 for _ in range(7)]
    paiwu=[]
    yangfang=[]
    gaoceng=[]
    types=[]
    for i in range(len(json_re)):
        dictOrder=json_re[i];
        name=dictOrder.get("name")
        nameS=name.split(":")
        if(nameS[0]=='排屋'):
            orderlist[0]=1
            paiwu.append(int(nameS[1]))
            orderlist[1]=paiwu
            types.append(1)
        if (nameS[0] == '洋房'):
            orderlist[2] = 1
            yangfang.append(int(nameS[1]))
            orderlist[3]=yangfang
            types.append(2)
        if (nameS[0] == '高层'):
            orderlist[4] = 1
            gaoceng.append(int(nameS[1]))
            orderlist[5] = gaoceng
            types.append(3)
    orderlist[6]=list(set(types))
    print(orderlist)
    r.set('type',str(orderlist))
    return "asdasd"

@app.route("/login",methods=("POST","GET"))
def login():

    return render_template("login.html")


@app.route("/auth",methods=("POST","GET"))
def loginauth():
    dict={'root':'123456','z':'c'}
    username=request.form.get("userName")
    password=request.form.get("password")
    session['user'] = username
    for key in dict.keys():
        if key==username:
            if dict.get(key)==password:
                return render_template("Submit.html")
            else:
                return redirect("/login")
            break
    return render_template("login.html")

@app.route("/3d",methods=("POST","GET"))
def three():
    print('我是3d，我能感受到')
    if request.method == "POST":
        b=request.data
        print('builds:')
        builds = eval(b.decode('utf8'))
        print(b)
        #此处应该修改整体
        ll = r.get('all')
        plans = eval(ll.decode('utf8'))

        print(operation.typeof(plans))
        print(builds)
        for plan in plans:
            if int(plan[0]) == 1:#此处应该是int（pid）的，明天再改成pid
                print(plan[4])
                plan[4] = builds
                print("我找到的plan为：")
                print(plan)
        r.set('all', str(plans))

        return '正在前往3d页面'





    else:
        pid = request.args.get("pid")

        ll = r.get('all')
        plans = eval(ll.decode('utf8'))

        plan0 = []  # 将要访问的那个方案

        for plan in plans:
            if plan[0] == int(pid):
                print('我找到了你要的方案')
                print(plan)
                plan0 = plan.copy()



        a=r.get("a").decode('utf8')

        data = {
            'all':plans,
            'pid':pid,
            'plan':plan0,
            'arr':a
        }

        return render_template("3d.html",data=data)


@app.route("/preview",methods=("POST","GET"))
def pre_three():
        # pid = request.args.get    Q("pid")
        # ll = r.get('all')
        # print(pid)
        # plans = ll.decode('utf8')
        # t=eval(plans)
        # print('即将跳转至3d页面')
        # print(operation.typeof(pid))
        # print(operation.typeof(t))
        # builds = r.get('builds')
        # b=builds.decode('utf8')
        # plan0=[]#将要访问的那个方案
        # print(t)
        # plan0=[]
        # for plan in t:
        #     if plan[0] == int(pid):
        #         print('我找到了你要的方案')
        #         print(plan)
        #         plan0 = plan.copy()
        # print(plan0)
        # data = {
        #     'builds':b,
        #     'all':t,
        #     'pid':pid,
        #     'plan':plan0
        # }

        return render_template("preview.html")


@app.route("/pre",methods=("POST","GET"))
def pre():
    pid = request.args.get('pid')
    ll = r.get('all')
    plans = eval(ll.decode('utf8'))

    print(pid)
    plan0 = []  # 将要访问的那个方案

    for plan in plans:
        if plan[0] == int(pid):
            print('我找到了你要的方案')
            print(plan)
            plan0 = plan.copy()


    data = {
            'pid':pid,
            'plan':plan0
        }

    return render_template("pre.html",data=data)


@app.route("/ppp",methods=("POST","GET"))
def ppp():
    return render_template("ppp.html")



@app.route("/3dsss",methods=("POST","GET"))
def sss():
    return render_template("3dsss.html")


app.run(host="0.0.0.0",port = 9527,debug = True)



